import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Input, InputNumber, Radio, Button, Flex, Table, message, RadioChangeEvent, Tooltip } from 'antd'
import type { TableColumnsType } from 'antd'
import './index.less'
import { SearchOutlined } from '@ant-design/icons'
import { ipcRendererInvoke, ipcRendererOn, ipcRendererRemoveListener } from '@common/desktopUtils'

const { TextArea } = Input
const options = [
  { value: 4, label: '大于' },
  { value: 5, label: '大于等于' },
  { value: 2, label: '小于' },
  { value: 3, label: '小于等于' }
]

interface DataType {
  key: React.Key
  project_id: string
  project_name: string
  advertiser_id: string
  stat_cost: number
  attribution_micro_game_0d_roi: number
  status: number
  error_message?: string
}

const columns: TableColumnsType<DataType> = [
  {
    title: '项目ID',
    dataIndex: 'project_id',
    width: 200
  },
  {
    title: '项目名称',
    dataIndex: 'project_name',
    width: 300
  },
  {
    title: '账户ID',
    dataIndex: 'advertiser_id',
    width: 200
  },
  {
    title: '消耗',
    dataIndex: 'stat_cost',
    width: 100
  },
  {
    title: '实时ROI',
    dataIndex: 'attribution_micro_game_0d_roi',
    width: 100
  },
  {
    title: '状态',
    key: 'operation',
    fixed: 'right',
    width: 100,
    render: (value, record) => {
      return record.status === 0 ? (
        <Tooltip placement="top" title={record.error_message}>
          <span
            style={{
              color: 'rgb(255, 77, 79)',
              cursor: 'pointer'
            }}
          >
            失败
          </span>
        </Tooltip>
      ) : (
        <span
          style={{
            color: 'rgb(22, 119, 255)',
            cursor: 'pointer'
          }}
        >
          成功
        </span>
      )
    }
  }
]
const str =
  '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
function getCurrentDate() {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
const names = {
  stat_cost: '项目消耗',
  attribution_micro_game_0d_roi: '实时ROI'
}
const defaultValue = {
  advertiser_ids: '',
  filters: [
    { field: 'stat_cost', type: 3, operator: 4, values: ['0'] },
    {
      field: 'attribution_micro_game_0d_roi',
      type: 3,
      operator: 4,
      values: ['0']
    }
  ],
  data_topic: 'BASIC_DATA',
  dimensions: ['cdp_project_id', 'cdp_project_name'],
  metrics: ['stat_cost', 'attribution_micro_game_0d_roi'],
  order_by: [
    { field: 'stat_cost', type: 'ASC' },
    { field: 'attribution_micro_game_0d_roi', type: 'ASC' }
  ],
  start_time: getCurrentDate(),
  end_time: getCurrentDate(),
  page_size: 100
}
function TableInfo() {
  const [messageApi, contextHolder] = message.useMessage()
  const [rowAds, setRowAds] = useState<Record<string, any>>({})
  const [tableData, setTableData] = useState<DataType[]>([])
  const [formValue, setFormValue] = useState<Record<string, any>>({
    ...defaultValue
    // advertiser_ids: '1827638232678922\n1827638173965323'
  })
  const [btnsLoading, setBtnsLoading] = useState<Record<string, boolean>>({
    open: false,
    close: false
  })
  const refUpdate = useRef<Record<string, any>>({})
  const adLength = useRef<number>(0)
  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setFormValue({
      ...formValue,
      advertiser_ids: e.target.value
    })
  }
  const handleChangeRadio = (e: RadioChangeEvent, index: number) => {
    const { filters } = formValue
    filters[index].operator = e.target.value
    setFormValue({
      ...formValue,
      filters: [...filters]
    })
  }
  const handleNumberChange = (value: number | null, index: number) => {
    const { filters } = formValue
    filters[index].values = [`${value || 0}`]
    setFormValue({
      ...formValue,
      filters: [...filters]
    })
  }
  const handleSearch = async () => {
    const { advertiser_ids, ...rest } = formValue
    const aids = advertiser_ids.split('\n').filter(Boolean)
    if (aids.length === 0) {
      await messageApi.open({
        type: 'error',
        content: '请输入广告账户ID'
      })
      return
    }
    aids.map(async (item) => {
      await ipcRendererInvoke('custom-report', {
        ...rest,
        advertiser_id: item.trim()
      })
    })
    adLength.current = aids.length
  }
  const handleUpdateAds = (_, result: any) => {
    refUpdate.current = {
      ...refUpdate.current,
      ...result
    }
    if (Object.keys(refUpdate.current).length === adLength.current && Object.keys(rowAds).length === adLength.current) {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
      const ads = Object.keys(refUpdate.current).reduce((previousValue: any[], currentValue) => {
        const rows = rowAds[currentValue]?.rows
        previousValue = [
          ...previousValue,
          ...(refUpdate.current[currentValue].errors || []).map((item) => {
            const find = rows.find((row) => row.dimensions.cdp_project_id * 1 === item.project_id)
            return {
              ...item,
              advertiser_id: currentValue,
              ...(find ? find.metrics : {}),
              project_name: find?.dimensions?.cdp_project_name,
              status: 0
            }
          }),
          ...(refUpdate.current[currentValue].project_ids || []).map((item) => {
            const find = rows.find((row) => row.dimensions.cdp_project_id * 1 === item)
            return {
              project_id: item,
              advertiser_id: currentValue,
              ...(find ? find.metrics : {}),
              project_name: find?.dimensions?.cdp_project_name,
              status: 1
            }
          })
        ]
        return previousValue
      }, [])
      setTableData([...ads])
      setBtnsLoading({
        close: false,
        open: false
      })
    }
    // const
  }
  useEffect(() => {
    ipcRendererOn('custom-report-result', (_, result: Record<string, any>) => {
      if (result) {
        setRowAds((prevState) => ({ ...prevState, ...result }))
      }
    })
    return () => {
      ipcRendererRemoveListener('custom-report-result', () => {})
      ipcRendererRemoveListener('custom-report', () => {})
    }
  }, [])
  useEffect(() => {
    if (Object.values(rowAds).filter(Boolean).length > 0) {
      ipcRendererOn('update-project-result', handleUpdateAds)
    }
    return () => {
      ipcRendererRemoveListener('update-project', () => {})
      ipcRendererRemoveListener('update-project-result', () => {})
    }
  }, [rowAds])
  const isDis = useMemo(() => Object.values(rowAds).filter(Boolean).length > 0, [rowAds])
  const handleRest = () => {
    setFormValue({
      ...defaultValue
    })
    setTableData([])
    setRowAds({})
    refUpdate.current = {}
    adLength.current = 0
  }

  const handleAllIn = (flag) => {
    setBtnsLoading({
      ...btnsLoading,
      [flag ? 'open' : 'close']: true
    })
    const schedule_time = flag ? str.replaceAll('0', '1') : str.replaceAll('1', '0')
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    Object.keys(rowAds).map(async (item) => {
      return ipcRendererInvoke('update-project', {
        advertiser_id: Number(item),
        data: rowAds[item].rows?.map((row) => ({
          project_id: Number(row.dimensions.cdp_project_id),
          schedule_time,
          schedule_scene: 'REALTIME'
        }))
      })
    })
  }

  return (
    <div className="container">
      {contextHolder}
      <h3 className="mb-8">广告账户ID</h3>
      <TextArea rows={8} placeholder="换行，可批量输入多个" value={formValue.advertiser_ids} onChange={handleChange} />
      <h3 className="mb-8 mt-16">
        广告账户ID
        <span className="primary">备注：只查询开启状态，且消耗大于0的项目</span>
      </h3>
      <div className="check-area">
        {formValue.filters?.map((item, index: number) => (
          <nav key={item.field}>
            <span>{names[item.field]}</span>
            <Radio.Group
              name="radiogroup"
              value={item.operator}
              options={options}
              onChange={(e) => handleChangeRadio(e, index)}
            />
            <InputNumber
              min={0}
              value={item.values[0] * 1}
              step="0.01"
              onChange={(e) => handleNumberChange(e, index)}
            />
          </nav>
        ))}

        <Button type="primary" icon={<SearchOutlined />} style={{ width: 96 }} size="large" onClick={handleSearch}>
          查询
        </Button>
      </div>
      <div className="options">
        <h3 className="mb-8">操作</h3>
        <Flex gap="small" wrap>
          <Button
            danger
            type="primary"
            size="large"
            disabled={!isDis}
            loading={btnsLoading.close}
            onClick={() => handleAllIn(false)}
          >
            全部关停
          </Button>
          <Button
            type="primary"
            size="large"
            disabled={!isDis}
            loading={btnsLoading.open}
            onClick={() => handleAllIn(true)}
          >
            全部开启
          </Button>
          <Button size="large" onClick={handleRest}>
            全部重置
          </Button>
        </Flex>
      </div>
      <div className="result">
        <h3 className="mb-8">结果</h3>
        {tableData.length > 0 ? (
          <div className="result-tip">
            {tableData.length} 个项目ID，共
            <span className="result-tip-error">{tableData.filter((i) => i.status === 0).length}</span>个
            <span className="result-tip-error">失败</span>
            ，共<span className="result-tip-success">{tableData.filter((i) => i.status === 1).length}</span>个
            <span className="result-tip-success">成功</span>
          </div>
        ) : null}

        <Table<DataType>
          columns={columns}
          dataSource={tableData}
          size="middle"
          key="project_id"
          bordered
          scroll={{
            x: 1000
          }}
        />
      </div>
    </div>
  )
}

export default TableInfo
